import routes from "@/config/routes";
import { Breadcrumb } from "antd";
import { useEffect, useState } from "react";
import { NavLink, useLocation } from "react-router-dom";

const GenBreadCrumb: React.FC = (props: any) => {
  const {} = props;
  const [route, setRoute] = useState<{ title: JSX.Element }[]>([]);
  const location = useLocation();
  function handleRoute() {
    let handleRoute: any = {};
    for (let [key, value] of Object.entries(routes)) {
      const arr = key.split(".");
      arr.splice(0, 1);
      handleRoute["/" + arr.join("/")] = value;
    }

    return handleRoute;
  }
  const routers = handleRoute();

  const genBreadCrumbArr = (path: string) => {
    const res = path.split("/").filter(Boolean);
    return res.map((_, index) => {
      let url = `/${res.slice(0, index + 1).join("/")}`;
      if (index + 1 == res.length) {
        return { title: routers[url]?.name };
      } else {
        return { title: <NavLink to={url}>{routers[url]?.name}</NavLink> };
      }
    });
  };
  useEffect(() => {
    const breadObj = genBreadCrumbArr(location.pathname);
    setRoute(breadObj);
  }, [location]);

  return <Breadcrumb items={route} />;
};

export default GenBreadCrumb;
